<?php

namespace app\home\controller;

// 引入公共控制器
use app\common\controller\Home;

class Team extends Home
{

    // 控制器初始化
    public function _initialize()
    {
        parent::_initialize();
        $this->CommissionModel = model('Business.Commission');
        $this->SubjectModel = model('Subject.Subject');
        $this->BusinessModel = model('Business.Business');
        $this->RecordModel = model('Business.Record');
    }

    // 海报
    public function poster()
    {
        // 获取当前域名
        // 获取协议名
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
        // 获取当前域名
        $host = $_SERVER['SERVER_NAME'] ? $_SERVER['SERVER_NAME'] : 'fastm.constqr.cn';
        // 拼接域名
        $domain =  $protocol . "://"  . $host;

        // 头像
        $avatar = isset($this->BusinessModel['avatar_text']) ? trim($this->BusinessModel['avatar_text']) : '';

        // 加密个人信息
        $id = isset($this->Business['id']) ? trim($this->Business['id']) : 0;
        $mobile =  isset($this->Business['mobile']) ? trim($this->Business['mobile']) : '';

        $token = md5($id . $mobile);

        // 海报底图
        $poster = isset($this->Business['poster_text']) ? trim($this->Business['poster_text']) : '';

        // url('地址表达式',['参数'],['URL后缀'],['域名'])(用于生成二维码)
        $url = url('home/index/login', ['token' => $token], true, true);

        // 生成二维码
        if ($this->request->isPost()) {
            // 实例化二维码插件
            $code = new \dh2y\qrcode\QRcode();

            // 设置二维码容错率
            $level = ['L', 'M'];
            $index = array_rand($level);

            // 获取二维码生成的路径
            $code_path = $code->png($url, false, 15, $level[$index])->getPath();

            // 二维码（需要绝对路径）
            $Qrcode = $domain . str_replace('\\', '/', $code_path);

            // var_dump($Qrcode);exit;
            // 做一张海报 创建图片的实例
            $PosterImg = imagecreatefromstring(file_get_contents($poster));
            $QrcodeImg = imagecreatefromstring(file_get_contents($Qrcode));
            $AvatarImg = imagecreatefromstring(file_get_contents($avatar));

            // 创建头像缩略图
            $AvatarThumb = imagecreatetruecolor(100, 100);
            // 重采样拷贝部分图像并调整大小
            imagecopyresampled($AvatarThumb, $AvatarImg, 0, 0, 0, 0, 100, 100, imagesx($AvatarImg), imagesy($AvatarImg));

            // 二维码图片的宽和高 获取新的尺寸
            list($QrcodeW, $QrcodeH) = getimagesize($Qrcode);

            // imagecopymerge — 拷贝并合并图像的一部分
            imagecopymerge($PosterImg, $QrcodeImg, 70, 250, 0, 0, $QrcodeW, $QrcodeH, 100);
            imagecopymerge($PosterImg, $AvatarThumb, 50, 40, 0, 0, 100, 100, 100);

            if ($host != 'fastm.constqr.cn') {
                // 服务器路径
                $font = "D:/develop/phpstudy_pro/WWW/thinkphp/1.5.2.20240906/public/assets/fonts/captcha.ttf";
            } else {
                // 服务器路径
                $font = "/www/sites/fastm.constqr.cn/index/fast-admin/public/assets/fonts/captcha.ttf";
            }

            // 文字昵称放到底图上面
            $black = imagecolorallocate($PosterImg, 0, 0, 0); // 字体颜色
            imagettftext($PosterImg, 20, 0, 180, 70, $black, $font, $this->Business['nickname']);

            //保留的二维码图片文件路径（准备用于删除）
            $PosterPath = "uploads/qrcode/{$token}.jpg";
            $results = imagejpeg($PosterImg, $PosterPath);

            if($host != 'fastm.constqr.cn')
            {
                //删除二维码图片、释放资源
                is_file(trim($code_path, '\\')) && @unlink(trim($code_path, '\\'));
            }
            else
            {
                $code_path = "/www/sites/fastm.constqr.cn/index/fast-admin/public" . trim($code_path, '\\');
                //删除二维码图片、释放资源
                is_file($code_path) && @unlink($code_path);
            }

            // 释放资源
            imagedestroy($PosterImg);
            imagedestroy($QrcodeImg);
            imagedestroy($AvatarImg);
            imagedestroy($AvatarThumb);

            //没有保留下来
            if (!$results) {
                $this->error("生成海报失败");
                exit;
            }

            $data = [
                'id' => $id,
                'poster' => '/' . $PosterPath
            ];

            $result = $this->BusinessModel->isUpdate(true)->save($data);

            if ($result === false) {
                //将保留下来二维码海报删除掉
                @is_file($PosterPath) && @unlink($PosterPath);
                $this->error('更新海报失败');
                exit;
            } else {
                //跟头像一样的道理，将旧的删掉
                $this->success('更新海报成功', null, "/" . $PosterPath);
                exit;
            }
        }

        $this->assign([
            'url' => $url,
            'Business' => $this->Business
        ]);

        return $this->view->fetch();
    }

    // 提现列表
    public function commission()
    {
        if ($this->request->isPost()) {
            $page = $this->request->param('page', 1, 'trim');
            $status = $this->request->param('status', 3, 'trim');

            $where = [
                'commission.parentid' => $this->Business['id'],
                'type' => 'subject'
            ];

            if ($status != 3) {
                $where['status'] = $status;
            }

            $list = $this->CommissionModel->with(['business', 'order'])->where($where)->page("$page, 10")->order('createtime desc')->select();
            // echo $this->CommissionModel->getLastSql();exit;

            // 总数
            $count = $this->CommissionModel->with(['business', 'order'])->where($where)->count();

            if ($list) {

                foreach ($list as $item) {
                    $subid = isset($item['order']['subid']) ? $item['order']['subid'] : 0;
                    $subject = $this->SubjectModel->find($subid);
                    $item['subject'] = $subject;
                }

                $data = [
                    'count' => $count,
                    'list' => $list
                ];

                $this->success('', '', $data);
            } else {
                $this->error('暂无更多数据');
            }
        }
        return $this->view->fetch();
    }

    //提现功能
    public function recover()
    {
        $comid = $this->request->param('comid', 0, 'trim');

        $commission = $this->CommissionModel->find($comid);

        if (!$commission) {
            $this->error('暂无提现记录');
            exit;
        }

        /*
            佣金记录表： 状态更新
            用户表： 余额更新
            消费记录表： 新增
        */
        $this->CommissionModel->startTrans();
        $this->BusinessModel->startTrans();
        $this->RecordModel->startTrans();

        $CommissionStatus = $this->CommissionModel->where(['id' => $comid])->update(['status' => '1']);

        if ($CommissionStatus === false) {
            $this->error($this->CommissionModel->getError());
            exit;
        }

        // 剩余余额
        $money = bcadd($this->Business['money'], $commission['amount'], 2);

        $BusinessData = [
            'id' => $this->Business['id'],
            'money' => $money
        ];

        $validate = [
            [
                'money' => ['number', 'egt:0'],
            ],
            [
                'money.number'  => '余额必须是数字类型',
                'money.egt'      => '余额不足请先充值',
            ]
        ];

        $BusinessStatus = $this->BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

        if ($BusinessStatus === false) {
            $this->CommissionModel->rollback();
            $this->error($this->BusinessModel->getError());
            exit;
        }

        $RecordData = [
            'total' => $commission['amount'],
            'busid' => $this->Business['id'],
            'content' => "提现佣金，￥{$commission['amount']}元"
        ];

        $RecordStatus = $this->RecordModel->validate('common/Business/Record')->save($RecordData);
        if ($RecordStatus === false) {
            $this->CommissionModel->rollback();
            $this->BusinessModel->rollback();
            $this->error($this->RecordModel->getError());
            exit;
        }

        if ($CommissionStatus === false || $BusinessStatus === false || $RecordStatus === false) {
            $this->CommissionModel->rollback();
            $this->BusinessModel->rollback();
            $this->RecordModel->rollback();
            $this->error('提现失败');
            exit;
        } else {
            $this->CommissionModel->commit();
            $this->BusinessModel->commit();
            $this->RecordModel->commit();
            $this->success('提现成功');
            exit;
        }
    }
}
